from afast_core.core_tools.encrypt_helper import md5
from afast_core.core_tools.jwt_helper import SimpleAuth
from infirmary_admin_src.infirmary_common.infirmary_controller import IBaseController
from infirmary_admin_src.infirmary_common.infirmary_controller.rest_controller_with_depends import \
    RestControllerWithDepends
from fastapi import Request

from infirmary_admin_src.infirmary_smart_admin.infirmary_biz.system.login.schemas import SchemaBase
from infirmary_admin_src.infirmary_smart_admin.infirmary_biz.system.login.services import LogicBusinesses
from infirmary_admin_src.infirmary_smart_admin.infirmary_utils.convert2_help import convert_dict_to_camel_case


class XParam(SchemaBase):
    '''
    账号密码登录参数
    '''
    loginName: str
    password: str
    captchaCode: str
    captchaUuid: str
    loginDevice: int = 1


class IController(IBaseController):
    '''
    定制相关约束检测函数逻辑步序
    '''

    def __init__(self, *, request: Request,
                 schema_param: XParam,
                 ):
        super().__init__(request=request)
        # 入参参数
        # 入参参数
        self.schema_param = schema_param


@RestControllerWithDepends()
class AuthloginController(IController):

    def business_login(self):
        pass
        # 记录到缓存中，便于进行检测验证码
        random_str = self.request.app.cache_house.get_key(self.schema_param.captchaUuid)
        if not random_str:
            self.response_ok = False
            self.response_msg = '验证码不能为空，请输入正确的验证码'
            return

        # 验证码码匹配
        if random_str and random_str != self.schema_param.captchaCode.upper():
            self.response_api_code = 30001
            self.response_ok = False
            self.response_msg = '验证码不正确，请输入正确的验证码'
            return

        # 开始读取用户信息
        result_user_info = LogicBusinesses.get_sys_employee_info_by_login_name(login_name=self.schema_param.loginName)
        if not result_user_info:
            self.response_api_code = 30001
            self.response_ok = False
            self.response_msg = '用户信息不存在，请输入正确用户名信息'
            return

        result_user_info_dept = LogicBusinesses.get_sys_employee_info_by_login_name_deptid(login_name=self.schema_param.loginName)
        if not result_user_info_dept:
            self.response_api_code = 30001
            self.response_ok = False
            self.response_msg = '用户信息所属部门信息不存在'
            return





        # 匹配密码信息
        if result_user_info.login_pwd.lower() != md5(self.schema_param.password).lower():
            pass
            self.response_api_code = 30001
            self.response_ok = False
            self.response_msg = '登入用户密码错误，请输入正确用户名密码'
            return

        if result_user_info.disabled_flag == 1:
            self.response_api_code = 30001
            self.response_ok = False
            self.response_msg = '当前用户已经被禁用，请联系客服！'
            return

        # 开始生成用户token以及其他信息
        # 写入部门编码ID，用于后续请求中限制数据获取


        _date = {
            'login_name': result_user_info.login_name,
            'employee_id': result_user_info.employee_id,
            'administrator_flag': result_user_info.administrator_flag,
            # 部门编号ID====对应的是医馆的渠道ID
            'department_code':result_user_info_dept[0].get('department_code'),
        }
        # 生成对于的此用户信息的token, 创建授权码，并设置过期的时间--授权码有效期为 24 * 31天
        isok, token = SimpleAuth.create_token_by_data(sub='zyx', data=_date, exp_time=60 * 60 * 2)
        if result_user_info.administrator_flag == 1:
            menuList = LogicBusinesses.get_sys_employee_menuList_by_admin_role()
            authorities = LogicBusinesses.get_sys_employee_authorities_by_admin_role()
            print("管理员的权限ID：",authorities)
        else:
            menuList = LogicBusinesses.get_sys_employee_menuList_by_admin_role_byEmployeeid(employee_id=result_user_info.employee_id)
            authorities = LogicBusinesses.get_sys_employee_authorities_by_admin_role_byEmployeeid(employee_id=result_user_info.employee_id)
        backdata = {
            # ============
            "token": token,
            'userId': result_user_info.id,
            'employeeId': result_user_info.id,
            'userType': "ADMIN_EMPLOYEE" if result_user_info.administrator_flag == 1 else '',
            'username': result_user_info.login_name,
            'userName': result_user_info.actual_name,
            'loginName': result_user_info.login_name,
            'actualName': result_user_info.actual_name,
            'gender': result_user_info.gender,
            'phone': result_user_info.phone,
            'departmentId': result_user_info.department_id,
            'departmentName': True if result_user_info.administrator_flag == 1 else False,
            'enabled': True if result_user_info.disabled_flag == 0 else False,
            "accountNonExpired": True,
            "accountNonLocked": True,
            "credentialsNonExpired": True,
            # ============
            'ip': None,
            'lastLoginIp': '',
            'lastLoginTime': None,
            'lastLoginUserAgent': None,
            # 用户角色享有的菜单列表
            "menuList": [{**{'apiPermsList': None}, **convert_dict_to_camel_case(v, passkey=['contextMenuId',
                                                                                             'createUserId',
                                                                                             'menuType',
                                                                                             'parentId',
                                                                                             ],
                                                                                 keepkey=['permsType', 'updateUserId',
                                                                                          'menuId', ],

                                                                                 ),
                          } for v in menuList] if menuList else [],
            # 用户角色有的权限标识
            "authorities": authorities,
        }
        return backdata
